"""
活动中心模型
包含社团管理、活动发布、报名管理等功能
"""

from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone
from django.core.exceptions import ValidationError
import re

User = get_user_model()


class Club(models.Model):
    """
    社团模型
    存储社团的基本信息
    """
    
    # 社团状态选择
    STATUS_CHOICES = [
        ('active', '活跃'),
        ('inactive', '不活跃'),
        ('suspended', '暂停'),
        ('disbanded', '已解散'),
    ]
    
    # 基础信息
    name = models.CharField(
        max_length=100,
        unique=True,
        verbose_name='社团名称'
    )
    
    description = models.TextField(
        verbose_name='社团简介'
    )
    
    logo = models.ImageField(
        upload_to='club_logos/',
        blank=True,
        null=True,
        verbose_name='社团logo'
    )
    
    # 社团信息
    category = models.CharField(
        max_length=50,
        verbose_name='社团类别'
    )
    
    founded_date = models.DateField(
        verbose_name='成立时间'
    )
    
    member_count = models.IntegerField(
        default=0,
        verbose_name='成员数量'
    )
    
    # 联系方式
    contact_person = models.CharField(
        max_length=50,
        verbose_name='联系人'
    )
    
    contact_phone = models.CharField(
        max_length=11,
        verbose_name='联系电话'
    )
    
    contact_email = models.EmailField(
        blank=True,
        verbose_name='联系邮箱'
    )
    
    # 状态信息
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='active',
        verbose_name='社团状态'
    )
    
    is_verified = models.BooleanField(
        default=False,
        verbose_name='是否认证'
    )
    
    # 时间信息
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间'
    )
    
    class Meta:
        verbose_name = '社团'
        verbose_name_plural = '社团'
        db_table = 'activity_clubs'
        ordering = ['-member_count', 'name']
    
    def __str__(self):
        return self.name
    
    def clean(self):
        # 验证联系电话格式
        if self.contact_phone:
            # 检查是否为11位数字
            if not re.match(r'^1[3-9]\d{9}$', self.contact_phone):
                raise ValidationError({"contact_phone": "请输入正确的11位手机号码"})
    
    def save(self, *args, **kwargs):
        # 在保存前执行clean方法进行验证
        self.clean()
        super().save(*args, **kwargs)


class ClubMember(models.Model):
    """
    社团成员模型
    记录社团成员信息
    """
    
    # 成员角色选择
    ROLE_CHOICES = [
        ('member', '普通成员'),
        ('officer', '干事'),
        ('vice_president', '副会长'),
        ('president', '会长'),
    ]
    
    club = models.ForeignKey(
        Club,
        on_delete=models.CASCADE,
        related_name='members',
        verbose_name='社团'
    )
    
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='club_memberships',
        verbose_name='用户'
    )
    
    role = models.CharField(
        max_length=20,
        choices=ROLE_CHOICES,
        default='member',
        verbose_name='成员角色'
    )
    
    join_date = models.DateTimeField(
        auto_now_add=True,
        verbose_name='加入时间'
    )
    
    is_active = models.BooleanField(
        default=True,
        verbose_name='是否活跃'
    )
    
    class Meta:
        verbose_name = '社团成员'
        verbose_name_plural = '社团成员'
        db_table = 'activity_club_members'
        unique_together = ['club', 'user']
        ordering = ['role', 'join_date']
    
    def __str__(self):
        return f"{self.user.username} - {self.club.name} ({self.get_role_display()})"


class Activity(models.Model):
    """
    活动模型
    存储活动的详细信息
    """
    
    # 活动状态选择
    STATUS_CHOICES = [
        ('not_started', '未开始报名'),
        ('registration_open', '报名中'),
        ('ongoing', '进行中'),
        ('completed', '已结束'),
        ('cancelled', '已取消'),
    ]
    
    # 活动类型选择
    TYPE_CHOICES = [
        ('academic', '学术讲座'),
        ('cultural', '文化活动'),
        ('sports', '体育活动'),
        ('volunteer', '志愿活动'),
        ('competition', '比赛竞赛'),
        ('party', '聚会活动'),
        ('other', '其他'),
    ]
    
    # 基础信息
    title = models.CharField(
        max_length=200,
        verbose_name='活动标题'
    )

    # 参与人数
    participant_count = models.IntegerField(
        default=0,
        verbose_name='参与人数'
    )
    
    description = models.TextField(
        verbose_name='活动描述'
    )
    
    club = models.ForeignKey(
        Club,
        on_delete=models.CASCADE,
        related_name='activities',
        null=True,
        blank=True,
        verbose_name='主办社团'
    )
    
    organizer = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='organized_activities',
        verbose_name='组织者'
    )
    
    # 活动类型和状态
    activity_type = models.CharField(
        max_length=20,
        choices=TYPE_CHOICES,
        verbose_name='活动类型'
    )
    
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='draft',
        verbose_name='活动状态'
    )
    
    # 时间信息
    start_time = models.DateTimeField(
        verbose_name='开始时间'
    )
    
    end_time = models.DateTimeField(
        verbose_name='结束时间'
    )
    
    registration_deadline = models.DateTimeField(
        verbose_name='报名截止时间'
    )
    
    # 地点信息
    location = models.CharField(
        max_length=200,
        verbose_name='活动地点'
    )
    
    # 人数限制
    max_participants = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='最大参与人数'
    )
    
    current_participants = models.IntegerField(
        default=0,
        verbose_name='当前报名人数'
    )
    
    # 费用信息
    is_free = models.BooleanField(
        default=True,
        verbose_name='是否免费'
    )
    
    fee = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=0.00,
        verbose_name='活动费用'
    )
    
    # 特殊设置
    allow_guest = models.BooleanField(
        default=False,
        verbose_name='是否允许非成员参加'
    )
    
    require_approval = models.BooleanField(
        default=False,
        verbose_name='是否需要审核'
    )
    
    # 时间信息
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间'
    )
    
    class Meta:
        verbose_name = '活动'
        verbose_name_plural = '活动'
        db_table = 'activity_activities'
        ordering = ['-start_time']
    
    def __str__(self):
        if self.club:
            return f"{self.title} - {self.club.name}"
        return self.title


class ActivityImage(models.Model):
    """
    活动图片模型
    存储活动相关的图片
    """
    
    activity = models.ForeignKey(
        Activity,
        on_delete=models.CASCADE,
        related_name='images',
        verbose_name='活动'
    )
    
    image = models.ImageField(
        upload_to='activity_images/',
        verbose_name='图片'
    )
    
    order = models.IntegerField(
        default=0,
        verbose_name='排序'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='上传时间'
    )
    
    class Meta:
        verbose_name = '活动图片'
        verbose_name_plural = '活动图片'
        db_table = 'activity_images'
        ordering = ['order', 'created_at']
    
    def __str__(self):
        return f"{self.activity.title} - 图片{self.order}"


class ActivityRegistration(models.Model):
    """
    活动报名模型
    记录用户的活动报名信息
    """
    
    # 报名状态选择
    STATUS_CHOICES = [
        ('pending', '待审核'),
        ('approved', '已通过'),
        ('rejected', '已拒绝'),
        ('cancelled', '已取消'),
        ('attended', '已参加'),
        ('absent', '未参加'),
    ]
    
    activity = models.ForeignKey(
        Activity,
        on_delete=models.CASCADE,
        related_name='registrations',
        verbose_name='活动'
    )
    
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='activity_registrations',
        verbose_name='报名用户'
    )
    
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='pending',
        verbose_name='报名状态'
    )
    
    # 报名信息
    contact_phone = models.CharField(
        max_length=11,
        verbose_name='联系电话'
    )
    
    special_requirements = models.TextField(
        blank=True,
        verbose_name='特殊要求'
    )
    
    # 审核信息
    reviewer = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='reviewed_registrations',
        verbose_name='审核人'
    )
    
    review_comment = models.TextField(
        blank=True,
        verbose_name='审核意见'
    )
    
    reviewed_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )
    
    # 时间信息
    registered_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='报名时间'
    )
    
    class Meta:
        verbose_name = '活动报名'
        verbose_name_plural = '活动报名'
        db_table = 'activity_registrations'
        unique_together = ['activity', 'user']
        ordering = ['-registered_at']
    
    def __str__(self):
        return f"{self.user.username} 报名了 {self.activity.title}"


class ActivityComment(models.Model):
    """
    活动评论模型
    用户对活动的评论和反馈
    """
    
    activity = models.ForeignKey(
        Activity,
        on_delete=models.CASCADE,
        related_name='comments',
        verbose_name='活动'
    )
    
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='activity_comments',
        verbose_name='评论用户'
    )
    
    content = models.TextField(
        verbose_name='评论内容'
    )
    
    rating = models.IntegerField(
        choices=[(i, i) for i in range(1, 6)],
        verbose_name='评分'
    )
    
    is_anonymous = models.BooleanField(
        default=False,
        verbose_name='是否匿名'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='评论时间'
    )
    
    class Meta:
        verbose_name = '活动评论'
        verbose_name_plural = '活动评论'
        db_table = 'activity_comments'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.user.username} 评论了 {self.activity.title}"
